#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System;
using System.Collections.Generic;
using NUnitGrid.Framework.Logging;
using NUnitGrid.Framework.NUnitGrid;
using NUnitGrid.Framework.Pipes;
using NUnitGrid.Protocol.Commands;
using NUnitGrid.Protocol.Responses;


namespace NUnitGrid.Protocol
{
    public class GridAppProtocol : IApplicationMessageListener, IGridProtocol
    {
        private readonly IProtocolCommandHandler[] commandHandlers;
        protected readonly ILogger logger;
        protected readonly IPipe pipe;
        protected readonly IProtocolTransactionFactory transactionFactory;
        protected List<IProtocolTransaction> currentTransactions = new List<IProtocolTransaction>();

        public GridAppProtocol(IPipe pipe, ILogger logger, IProtocolTransactionFactory transactionFactory,
                               IProtocolCommandHandler[] commandHandlers)
        {
            this.pipe = pipe;
            this.logger = logger;
            this.commandHandlers = commandHandlers;
            this.transactionFactory = transactionFactory;
        }

        public void OnMessageReceived(string message)
        {
            var handled = false;

            if (message.StartsWith("Command."))
            {
                handled = OnReceivedCommand(message);

                if (!handled)
                {
                    logger.Error.Write("Received unknown command: '{0}'", message);
                }
            }
            else if (message.StartsWith("Response."))
            {
                handled = OnReceivedResponse(message);

                if (!handled)
                {
                    logger.Error.Write("Unable to match response to sent command: '{0}'", message);
                }
            }
            else
            {
                logger.Error.Write("Received invalid message: '{0}'", message);
            }
        }

        public void Start()
        {
            currentTransactions.Clear();
            pipe.Start();
            pipe.Connect();
        }

        public void ReadInfo(IReadInfoListener listener)
        {
            var transaction = transactionFactory.CreateReadInfoTransaction(listener);
            currentTransactions.Add(transaction);
            transaction.SendCommand();
        }

        public void RunAsProcess(IGridTaskTransactionListener taskListener, string fileName, string clientMachineName,
                                 string workingDirectory, string commandLine, TimeSpan timeLimit,
                                 string enviromentVariable, string enviromentVariableValue, Guid sessionID)
        {
            var transaction = transactionFactory.CreateRunAsProcessTransaction(taskListener,
                                                                               clientMachineName,
                                                                               workingDirectory, fileName,
                                                                               commandLine, timeLimit,
                                                                               enviromentVariable,
                                                                               enviromentVariableValue, sessionID);
            currentTransactions.Add(transaction);
            transaction.SendCommand();
        }

        public void StopAllGridTasks(ITaskProgressListener taskListener)
        {
            var transaction = transactionFactory.StopAllGridTasksTransaction(taskListener);
            Send(transaction);
        }

        public void SendClientGridLoadingUpdate(int pendingTasks, int runningTasks)
        {
            var transaction = transactionFactory.ClientGridLoadingUpdate(new NullTaskProgressListener(), pendingTasks,
                                                                         runningTasks);
            Send(transaction);
        }

        public void SendMetricsUpdate(int busyNodesCount, int onlineNodesCount, int pendingTasksCount)
        {
            var transaction = transactionFactory.GridMetricsUpdate(new NullTaskProgressListener(), busyNodesCount,
                                                                   onlineNodesCount, pendingTasksCount);
            Send(transaction);
        }

        public void Stop()
        {
            pipe.Stop();
            currentTransactions.Clear();
        }

        private bool OnReceivedCommand(string command)
        {
            var handled = false;
            foreach (var handler in commandHandlers)
            {
                if (handler.CanHandle(command))
                {
                    handler.Handle(command);
                    handled = true;
                    break;
                }
            }
            return handled;
        }

        private bool OnReceivedResponse(string response)
        {
            logger.Verbose.Write("Received response: {0}", response);

            var handled = false;

            IProtocolTransaction matchingTransaction = null;
            foreach (var transaction in currentTransactions)
            {
                if (transaction.IsValidReponse(response))
                {
                    matchingTransaction = transaction;
                    break;
                }
            }

            if (matchingTransaction != null)
            {
                currentTransactions.Remove(matchingTransaction);
                matchingTransaction.ParseResponse(response);
                handled = true;
            }
            else
            {
                logger.Warning.Write("Unknown or unexpected response: '{0}'", response);
            }

            return handled;
        }

        private void Send(IProtocolTransaction transaction)
        {
            currentTransactions.Add(transaction);
            transaction.SendCommand();
        }
    }
}